<template>
  <div class="container">
    <div class="tabs-lb">
      <span>服务验证</span>
      <button class="btn_operation_add" @click="$router.back()">返回</button>
      <button @click="$router.push('/signGuide')" class="btn_operation_add">签名指南</button>
    </div>
    <!-- <div class="sfzsb">
      <div class="title">安全认证</div>
      <div class="item">
        <span>密钥：</span>
        <el-select v-model="ak" style="width: 100%" @change="myChange">
          <el-option
            v-for="(item, index) in myList"
            :key="index"
            :label="item.myms"
            :value="item.ak"
          >
          </el-option>
        </el-select>
      </div>
    </div>-->
    <div class="nlxq">
      <div class="title">请求参数</div>
      <div class="group-title">
        <img
          class="cursor"
          v-if="isShowList.cationShow"
          @click="ShowClike('cation')"
          src="~@/assets/img/grzx/箭头-上.png"
        />
        <img class="cursor" v-else @click="noneClike('cation')" src="~@/assets/img/grzx/箭头-下.png" />
        <span class="ml10">安全认证</span>
      </div>
      <div v-if="isShowList.cationShow" class="secure-cation">
        <div class="item">
          <span>ak</span>
          <el-input v-model="ak"></el-input>
        </div>
        <div class="item">
          <span>sk</span>
          <el-input v-model="sk"></el-input>
        </div>
      </div>
      <template v-if="urlList.length">
        <div class="group-title">
          <img
            class="cursor"
            v-if="isShowList.urlShow"
            @click="ShowClike('url')"
            src="~@/assets/img/grzx/箭头-上.png"
          />
          <img class="cursor" v-else @click="noneClike('url')" src="~@/assets/img/grzx/箭头-下.png" />
          <span class="ml10">请求参数(URL)</span>
        </div>
        <el-form v-if="isShowList.urlShow" label-width="140px" :model="urlForm">
          <el-form-item v-for="item in urlList" :key="item.id" :label="item.cs">
            <el-input v-model="item.zh"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template v-if="headerList.length">
        <div class="group-title">
          <img
            class="cursor"
            v-if="isShowList.headerShow"
            @click="ShowClike('header')"
            src="~@/assets/img/grzx/箭头-上.png"
          />
          <img class="cursor" v-else @click="noneClike('header')" src="~@/assets/img/grzx/箭头-下.png" />
          <span class="ml10">请求参数(HEADER)</span>
        </div>
        <el-form v-if="isShowList.headerShow" label-width="140px" :model="headerForm">
          <el-form-item v-for="item in headerList" :key="item.id" :label="item.cs">
            <el-input v-model="item.zh" :readonly="item.readonly"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template v-if="bodyList.length">
        <div class="group-title">
          <img
            class="cursor"
            v-if="isShowList.bodyShow"
            @click="ShowClike('body')"
            src="~@/assets/img/grzx/箭头-上.png"
          />
          <img class="cursor" v-else @click="noneClike('body')" src="~@/assets/img/grzx/箭头-下.png" />
          <span class="ml10">请求参数(BODY)</span>
        </div>
        <el-form
          v-if="isShowList.bodyShow"
          label-width="140px"
          ref="bodyRef"
          :model="bodyForm"
          :rules="bodyRole"
        >
          <el-form-item v-for="item in bodyList" :key="item.id" :label="item.cs" :prop="item.cs">
            <el-input v-model="bodyForm[item.cs]" style="width:50% "></el-input>
            <div class="itemMs" v-if="item.sm">
              <img src="~@/assets/img/grzx/疑问.png" alt />
              <span>{{item.sm}}</span>
            </div>
            <!-- <el-input disabled v-model="item.sm" style="width:49%; margin-left:10px"></el-input> -->
          </el-form-item>
        </el-form>
      </template>
      <div class="btn-ts">
        <el-button type="success" @click="tsData">调试</el-button>
      </div>
      <div class="title">请求结果</div>
      <pre class="pre" v-html="tsjg"></pre>
    </div>
  </div>
</template>
<script>
import jkglService from '@/api/jkgl'
import myglService from '@/api/mygl'
import axios from 'axios'
import { getSign } from '@/utils/sign.js'
export default {
  data() {
    return {
      jkbh: '',
      urlForm: {},
      headerForm: {},
      bodyForm: {},
      // 配置请求参数
      urlList: [],
      headerList: [
        { readonly: true, id: 'appId', zh: '', cs: 'appId' },
        { readonly: true, id: 'ts', zh: '', cs: 'ts' },
        { readonly: true, id: 'sign', zh: '', cs: 'sign' }
      ],
      bodyList: [],
      nlxq: {},
      tsjg: '',
      ak: '',
      sk: '',
      myList: [],
      // 规则校验
      bodyRole: {},
      isShowList: {
        urlShow: true,
        headerShow: true,
        bodyShow: true,
        cationShow: true,
      },
    }
  },
  mounted() {
    // 获取路由信息
    this.getRouter()
    // 获取安全认证表格
    this.getAqrzList()


  },
  methods: {
    /* 获取路由信息 */
    getRouter() {
      if (this.$route.query.cs) {
        this.jkbh = this.$route.query.cs
        // 获取能力详情
        this.getNlxq()
      }
    },
    /*
     * 获取安全认证表格
     */
    getAqrzList() {
      const params = {
        filter: {
          myms: '',
          myzt: '已启用'
        },
        orderBy: '',
        pageNum: 1,
        pageSize: 100
      }
      myglService
        .queryMy(params)
        .then(res => {
          this.myList = res.list || []
          this.ak = res.list[0].ak;
          this.sk = res.list[0].sk;
        })
        .catch(err => {
          !err.isError &&
            this.$message({ type: 'warning', message: err.message })
        })
    },
    myChange() {
      this.sk = this.myList.find(item => item.ak == this.ak).sk

      // // appId
      // const appId = this.headerList.find(item => item.cs === 'appId')
      // appId.zh = this.ak

      // // ts
      // const ts = this.headerList.find(item => item.cs === 'ts')
      // ts.zh = new Date().getTime()

      // // sign
      // const sign = this.headerList.find(item => item.cs === 'sign')
      // sign.zh = getSign(this.ak, this.sk, ts.zh)
    },
    /*
     * 获取调试信息
     */
    getNlxq() {
      const params = {
        jkbh: this.jkbh
      }
      jkglService
        .getJkdy(params)
        .then(res => {
          // 组装请求参数
          this.nlxq = res
          this.getFormList(res)
        })
        .catch(err => {
          !err.isError &&
            this.$message({ type: 'warning', message: err.message })
        })
    },

    /* 获取表单 */
    getFormList(res) {
      this.urlList = res.urlcs ? JSON.parse(res.urlcs) : []
      this.headerList = res.headercs
        ? [...this.headerList, ...JSON.parse(res.headercs)]
        : []
      this.bodyList = res.qqcs ? JSON.parse(res.qqcs) : []
      this.bodyForm = {}
      this.bodyList.forEach(item => {
        this.$set(this.bodyForm, item.cs, item.mrz);
        this.bodyRole[item.cs] = [{ required: true, message: '请输入内容', trigger: 'blur' }];
        if (item.sfbx === 'Y') {
          this.bodyRole[item.cs][0].required = true
        } else {
          this.bodyRole[item.cs][0].required = false
        }
      })
    },
    ShowClike(data) {
      if (data === 'url') {
        this.isShowList.urlShow = !this.isShowList.urlShow;
        return
      }

      if (data === 'header') {
        this.isShowList.headerShow = !this.isShowList.headerShow;
        return
      }

      if (data === 'body') {
        this.isShowList.bodyShow = !this.isShowList.bodyShow;
        return
      }

      if (data === 'cation') {
        this.isShowList.cationShow = !this.isShowList.cationShow;
        return
      }
    },
    noneClike(data) {
      if (data === 'url') {
        this.isShowList.urlShow = !this.isShowList.urlShow;
        return
      }

      if (data === 'header') {
        this.isShowList.headerShow = !this.isShowList.headerShow;
        return
      }

      if (data === 'body') {
        this.isShowList.bodyShow = !this.isShowList.bodyShow;
        return
      }

      if (data === 'cation') {
        this.isShowList.cationShow = !this.isShowList.cationShow;
        return
      }
    },

    /*
     * 调试
     */
    async tsData() {
      if (this.bodyList.length > 0) {
        this.$refs.bodyRef.validate(async (valid) => {
          if (valid) {
            // 设置默认token
            const token = window.sessionStorage.getItem('token')
            axios.defaults.headers['tf_token'] = token || ''
            // 签名
            // appId
            const appId = this.headerList.find(item => item.cs === 'appId')
            appId.zh = this.ak
            // ts
            const ts = this.headerList.find(item => item.cs === 'ts')
            ts.zh = new Date().getTime()
            // sign
            const sign = this.headerList.find(item => item.cs === 'sign')
            sign.zh = getSign(this.ak, this.sk, ts.zh)

            // const ak = this.ak
            // const sk = this.sk
            // const ts = new Date().getTime()
            // axios.defaults.headers['sign'] = getSign(ak, sk, ts)
            // axios.defaults.headers['appId'] = ak
            // axios.defaults.headers['ts'] = ts

            // url地址参数
            let url = this.nlxq.bldz
            for (const el of this.urlList) {
              url = url + `${url.split('?').length > 1 ? '&' : '?'}${el.cs}=${el.zh}`
            }

            for (let el of this.headerList) {
              axios.defaults.headers[el.cs] = el.zh
            }
            // let params = {}
            // for (let el of this.bodyList) {
            //   params[el.cs] = el.mrz
            // }
            let res = {}
            if (this.nlxq.qqfs === 'POST') {
              res = await axios.post(url, this.bodyForm)
            } else {
              res = await axios.get(url, this.bodyForm)
            }
            this.tsjg = JSON.stringify(res.status ? res.data : res, null, 4)
          }
        })
      } else {
        // 设置默认token
        const token = window.sessionStorage.getItem('token')
        axios.defaults.headers['tf_token'] = token || ''
        // 签名
        // appId
        const appId = this.headerList.find(item => item.cs === 'appId')
        appId.zh = this.ak
        // ts
        const ts = this.headerList.find(item => item.cs === 'ts')
        ts.zh = new Date().getTime()
        // sign
        const sign = this.headerList.find(item => item.cs === 'sign')
        sign.zh = getSign(this.ak, this.sk, ts.zh)

        // const ak = this.ak
        // const sk = this.sk
        // const ts = new Date().getTime()
        // axios.defaults.headers['sign'] = getSign(ak, sk, ts)
        // axios.defaults.headers['appId'] = ak
        // axios.defaults.headers['ts'] = ts

        // url地址参数
        let url = this.nlxq.bldz
        for (const el of this.urlList) {
          url = url + `${url.split('?').length > 1 ? '&' : '?'}${el.cs}=${el.zh}`
        }

        for (let el of this.headerList) {
          axios.defaults.headers[el.cs] = el.zh
        }
        // let params = {}
        // for (let el of this.bodyList) {
        //   params[el.cs] = el.mrz
        // }
        let res = {}
        if (this.nlxq.qqfs === 'POST') {
          res = await axios.post(url, this.bodyForm)
        } else {
          res = await axios.get(url, this.bodyForm)
        }
        this.tsjg = JSON.stringify(res.status ? res.data : res, null, 4)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  .sfzsb {
    margin-top: 20px;
    width: 100%;
    padding: 40px 30px;
    background: #fff;
    border: solid 1px #cecece;
    .title {
      font-size: 20px;
      font-weight: bold;
      color: #333;
    }
  }
  .nlxq {
    margin-top: 20px;
    width: 100%;
    padding: 40px 30px;
    background: #fff;
    border: solid 1px #cecece;

    .title {
      font-size: 20px;
      font-weight: bold;
      color: #333;
    }

    .group-title {
      width: 100%;
      height: 50px;
      line-height: 50px;
      float: left;
      border-bottom: 1px solid #f5f5f5;
      margin-bottom: 10px;
      span {
        position: relative;
        margin-left: 15px;
        color: #333333;
        font-weight: bold;
      }
      span:before {
        content: "";
        position: absolute;
        top: 3px;
        left: -9px;
        width: 4px;
        height: 18px;
        background-color: #0e69ff;
      }
    }

    .btn-ts {
      width: 100%;
      height: 40px;
      text-align: center;
    }
    .pre {
      width: 100%;
      height: 300px;
      border: solid 1px #cecece;
      overflow: auto;
      margin-top: 20px;
    }
  }
}
.signGuide {
  font-size: 20px;
  margin-left: 10px;
  cursor: pointer;
}

.secure-cation {
  display: flex;
  width: 100%;
  background: #fff;
  padding-bottom: 10px;
  .item {
    width: 50%;
    display: flex;
    align-items: center;
    // margin-top: 20px;
    > span {
      display: inline-block;
      width: 170px;
      text-align: right;
      padding-right: 10px;
    }
  }
}

.itemMs {
  display: inline-block;
  margin-left: 10px;
  width: 49%;
  word-break: break-all;
  span {
    margin-left: 5px;
  }
}

::v-deep .el-form-item__content {
  line-height: 15px;
}
</style>
